package com.zhixianggou.caibaobox.user.shiro.realms;


import com.zhixianggou.caibaobox.commons.utils.JedisUtil;
import com.zhixianggou.caibaobox.user.dao.UserMapper;
import com.zhixianggou.caibaobox.user.entities.User;
import com.zhixianggou.caibaobox.user.shiro.ShiroUser;
import com.zhixianggou.caibaobox.user.shiro.tokens.PhonePwdToken;
import jakarta.annotation.Resource;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class PhonePwdRealm extends AuthorizingRealm {

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


    /**
     * 必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return true;
    }

    @Resource
    UserMapper userMapper;


    /**
     * 认证
     * @param authcToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
        PhonePwdToken token = (PhonePwdToken) authcToken;
        String userName = token.getUsername();
        String pwd = String.valueOf(token.getPassword());
        ShiroUser shiroUser = new ShiroUser();
        User user = userMapper.selectByAccountPwd(userName, pwd);

        if(user == null){
            throw new UnknownAccountException();
        }

        if(user.getIsBan() == 1){
            throw new DisabledAccountException();
        }

        shiroUser.setUserId(user.getId());
        shiroUser.setUsername(user.getAccount());
        String jedisSessionIdKey = "shiro_user_session_id:" + userName;

        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(shiroUser, pwd, getName());

        JedisUtil.getInstance().add(jedisSessionIdKey,authcInfo.getPrincipals().toString());
        return authcInfo;
    }
}
